#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os.path
from run_command import run_command


def compile_file(arkcompiler_tool_path, arktsconfig_file, input_file, output_file):
    (path, name) = os.path.split(arkcompiler_tool_path)
    cmd = [os.path.join('.', name, 'es2panda'),
           '--arktsconfig', arktsconfig_file,
           '--opt-level=0',
           '--output', output_file,
           input_file]

    env = os.environ.copy()
    env['LD_LIBRARY_PATH'] = f'{arkcompiler_tool_path}'

    run_command(cmd, path, env)


def link(arkcompiler_tool_path, output_file, input_files):
    (path, name) = os.path.split(arkcompiler_tool_path)
    cmd = [os.path.join('.', name, 'ark_link'),
           '--output', output_file,
           '--', *input_files]

    env = os.environ.copy()
    env['LD_LIBRARY_PATH'] = f'{arkcompiler_tool_path}'

    run_command(cmd, path, env)


def gen_pa(arkcompiler_tool_path, input_file, output_file):
    (path, name) = os.path.split(arkcompiler_tool_path)
    cmd = [os.path.join('.', name, 'ark_disasm_static'),
           input_file, output_file]

    env = os.environ.copy()
    env['LD_LIBRARY_PATH'] = f'{arkcompiler_tool_path}'

    run_command(cmd, path, env)


def run_abc(arkcompiler_tool_path, boot_file_path, abc_file, entry_point):
    (path, name) = os.path.split(arkcompiler_tool_path)
    cmd = [os.path.join('.', name, 'ark'),
           '--boot-panda-files', boot_file_path,
           '--load-runtimes=ets', abc_file, entry_point] # entry_point default: 'main.ETSGLOBAL::main'

    env = os.environ.copy()
    env['LD_LIBRARY_PATH'] = f'{arkcompiler_tool_path}'

    run_command(cmd, path, env)
